#include "singlemultichat.h"
#include "ui_singlemultichat.h"
#include <QMutex>
#include <QDebug>

extern std::map<std::string, std::map<std::string, std::vector<std::string> > >global_multi_ip2msg;
extern QMutex global_multi_ip2msg_mutex;

SingleMultiChat::SingleMultiChat(QWidget *parent, QString multi_ip) :
    QMainWindow(parent),
    ui(new Ui::SingleMultiChat),
    multi_ip_addr_(multi_ip),
    chat_client(ChatClient::getChatClientInstance())
{
    ui->setupUi(this);
    timer = new QTimer(this);
    connect(timer,SIGNAL(timeout()),this,SLOT(showSync()));
    timer->start(100);
}

SingleMultiChat::~SingleMultiChat()
{
    delete ui;
}

void SingleMultiChat::showSync() {
    global_multi_ip2msg_mutex.lock();
    //qDebug() << multi_ip_addr_;
    if (global_multi_ip2msg.find(multi_ip_addr_.toStdString()) != global_multi_ip2msg.end()) {
        std::map<std::string, std::vector<std::string> >ip2msg = global_multi_ip2msg[multi_ip_addr_.toStdString()];
        global_multi_ip2msg.erase(multi_ip_addr_.toStdString());
        QString tmp;
        std::vector<std::string> msg_vec;
        for (auto p_ip = ip2msg.begin(); p_ip != ip2msg.end(); ++p_ip) {
            msg_vec = p_ip->second;
            for (auto iter = msg_vec.begin(); iter != msg_vec.end(); ++iter) {
                tmp = QString::fromStdString(p_ip->first);
                tmp += ":";
                tmp += QString::fromStdString(*iter);
                tmp += "\n";
                qDebug() << tmp;
                ui->textEdit->append(tmp);
            }
        }
    }
    global_multi_ip2msg_mutex.unlock();
}

void SingleMultiChat::on_send_clicked()
{
    QString msg = ui->chat_dialog->text();
    ui->chat_dialog->clear();
    ui->textEdit->append(msg);
    chat_client.sendMultiMsgSlots(multi_ip_addr_.toStdString(), msg.toStdString());
}
